package net.adriana.esaytool.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import net.adriana.esaytool.Logger;


/**
 * 类型转换Util
 * @author Administrator
 *
 */
public class ConvertUtil {

	public static Object convert(Object value, Class<? extends Object> type){
		if(value == null || value.equals("")){ return value; }
		//类型不是date
		if(!type.toString().equals("class java.util.Date")){
			//数字类型
			if(type == int.class){
				return Integer.parseInt((String)value);
			}
			//字符串类型
			if(type == String.class){
				return (String)value;
			}
		}
		
		String str = (String)value;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = sdf.parse(str);
			return date;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String castToCamelCase(String value, boolean isUpper){
		if(isCamelCase(value,isUpper)) return value;
		else {
			if(value.contains("_")){
				String[] values = value.split("_");
				if(isUpper) value = ""; else value = values[0];
				for (int i = 0; i < values.length; i++) {
					if(i == 0)continue;
					values[i] = values[i].substring(0, 1).toUpperCase() + values[i].substring(1);
					value += values[i];
				}
				Logger.log(Logger.DEBUG, "转换成驼峰命名法成功 " + value);
				return value;
			}
			Logger.log(Logger.ERROR, "转换成驼峰命名法失败 " + value);
			return value;
		}
	}
	
	
	public static boolean isCamelCase(String value, boolean isUpper){
		String pattern = "^[a-z]+([A-Z][a-z]+)$";
		if(isUpper) pattern = "^([A-Z][a-z]+)+$";
		if(Pattern.matches(pattern, value)) return true;
		else return false;
	}
	
	public static String castTypeName(String type){
		if(type.contains("varchar") || type.contains("text"))return "String";
		else if(type.contains("int"))return "Integer";
		else if(type.contains("datetime"))return "Date";
		return type;
	}
}
